#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import wraps
from datetime import datetime, timedelta
from werkzeug.contrib.cache import BaseCache
from werkzeug.wrappers import Response
from ..globals import request


class MongoCache(BaseCache):
    def __init__(self, collection, default_timeout=300, key_prefix=None):
        self.collection = collection
        self.default_timeout = default_timeout
        self.key_prefix = key_prefix

    def get(self, key):
        if self.key_prefix:
            key = self.key_prefix + key
        now = datetime.now()
        doc = self.collection.find_one({
                "_id": key,
                "_expire": {"$gt": now},
        })
        if doc:
            return doc["value"]

    def delete(self, key):
        if self.key_prefix:
            key = self.key_prefix + key
        self.collection.remove({"_id": key})

    def set(self, key, value, timeout=None):
        if timeout is None:
            timeout = self.default_timeout
        if self.key_prefix:
            key = self.key_prefix + key
        now = datetime.now()
        expire = now + timedelta(seconds=timeout)
        doc = { "_id": key,
                "_expire": expire,
                "value": value,
              }
        self.collection.save(doc)

    def clearExpired(self):
        self.collection.remove({"_expire": {"$lt": datetime.now()}})


def cache_page(cache, _lambda, timeout=None):
    def wrapper(func):
        @wraps(func)
        def new_func():
            key = _lambda()
            if request.args.get("_refresh"):
                data = None
            else:
                data = cache.get(key)
            if data is None:
                resp = func()
                if resp.status_code == 200:
                    cache.set(key, "".join(resp.response), timeout)
            else:
                resp = Response(data)
            return resp
        return new_func
    return wrapper
